from django.db import models
from utilities import urlutil
import feedparser

class Feed(models.Model):
    url_hash = models.CharField(max_length=32, primary_key=True)
    url = models.URLField(blank=False, null=False)
    title = models.CharField(max_length=50, blank=True)
    description = models.CharField(max_length=150, blank=True)
    language = models.CharField(max_length=5, default='en')
    
    # http://feedparser.org/docs/http-etag.html
    etag = models.CharField(max_length=50, blank=True)
    last_modified = models.DateTimeField(null=True, blank=True)
    
    last_checked = models.DateTimeField(null=True, blank=True)
    
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    
    def __unicode__(self):
        return u"Feed %s" % self.url
    
    def download_info(self):
        """Download information about the feed. 
        
        If there is any new post it should be created."""
        p = feedparser.parse(self.url, 
                             etag=self.etag, 
                             modified=self.last_modified)
        
        # status 304: the feed has not changed since last time checked
        if not p.status == 304:
            self.title = p.feed.title
            self.description = p.feed.description
            self.language = p.feed.language
            self.etag = p.etag
        
    
    def create(url):
        """Factory method that creates and returns a Feed-object."""
        url_hash = urlutil.generate_hash(url)
        f, created = Feed.objects.get_or_create(url_hash=url_hash)
        if created:
            f.url = urlutil.normalize(url)
            f.download_info()
        
        return f, created
    create = staticmethod(create)
            
        
        